/**
 * 
 */
package com.hengpeng.msls.tools;


public class HexUtils {

	private static final char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7',
        '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
	
	
	public static String byte2hex(byte[] b) {
		StringBuffer sb = new StringBuffer();
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) {
				sb.append("0").append(stmp);
			} else {
				sb.append(stmp);
			}
		}
		return sb.toString().toUpperCase();
	}

	
	public static byte[] hex2byte(String hex) {
		byte[] ret = new byte[8];
		byte[] tmp = hex.getBytes();
		for (int i = 0; i < 8; i++) {
			ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
		}
		return ret;
	}

	
	public static byte uniteBytes(byte src0, byte src1) {
		byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
				.byteValue();
		_b0 = (byte) (_b0 << 4);
		byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
				.byteValue();
		byte ret = (byte) (_b0 ^ _b1);
		return ret;
	}

	public static final byte[] fromHex(String b) {
	    char[] data = b.toCharArray();
	    int l = data.length;
	
	    byte[] out = new byte[l >> 1];
	    int i = 0;
	    for (int j = 0; j < l;) {
	        int f = Character.digit(data[(j++)], 16) << 4;
	        f |= Character.digit(data[(j++)], 16);
	        out[i] = (byte) (f & 0xFF);
	        ++i;
	    }
	
	    return out;
    }
	
    public static final String toHex(byte[] b) {
        char[] buf = new char[b.length * 2];
        int j;
        int i = j = 0;
        for (; i < b.length; ++i) {
            int k = b[i];
            buf[(j++)] = hex[(k >>> 4 & 0xF)];
            buf[(j++)] = hex[(k & 0xF)];
        }
        return new String(buf);
    }
}
